﻿using Exam.Repository.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Exam.Repository.Instance
{
    public class MySql_Repository<T> : I_Repository<T> where T : class, new()
    {
        private readonly DbContext _dbContext;
        public MySql_Repository(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void Add(T t)
        {
           _dbContext.Set<T>().Add(t);
        }

        public void AddRange(IEnumerable<T> ie)
        {
           _dbContext.Set<T>().AddRange(ie);
        }

        public void Delete(T t)
        {
            _dbContext.Set<T>().Remove(t);
        }

        public void DeleteRange(IEnumerable<T> ie)
        {
            _dbContext.Set<T>().RemoveRange(ie);
        }

        public T Find(params object[] keys)
        {
            return _dbContext.Set<T>().Find(keys);
        }

        /// <summary>
        /// 通用查询
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IQueryable<T> QueryAll(Expression<Func<T, bool>> where = null)
        {
           
            var iq=(IQueryable<T>)_dbContext.Set<T>();
            if (where != null)
            {
                iq=iq.Where(where);
            }
            return iq;
        }
      
        public IQueryable<T> QueryAll<type>(bool isAsc, Expression<Func<T, type>> order, Expression<Func<T, bool>> where = null)
        {
            var iq = this.QueryAll(where);
            return isAsc ? iq.OrderBy(order) : iq.OrderByDescending(order);
        }

        public IQueryable<T> QueryAll<type>(out int total, int skip, int limit, bool isAsc, Expression<Func<T, type>> order, Expression<Func<T, bool>> where = null)
        {
            var iq = this.QueryAll(isAsc, order, where);
            total=iq.Count();
            return iq.Skip(skip).Take(limit);
        }

        

        public int SaveChanges()
        {
           return _dbContext.SaveChanges();
        }

        public void Update(T t)
        {
            _dbContext.Entry<T>(t).State = EntityState.Modified;
        }

        public void UpdateRange(IEnumerable<T> ie)
        {
            foreach (var item in ie)
            {
                _dbContext.Entry<T>(item).State = EntityState.Modified;
            }
        }
    }
}
